package auto.app.util;

import cn.hutool.core.io.IoUtil;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

import org.apache.poi.util.IOUtils;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.springframework.http.MediaType;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * [Description]: 文件util
 *
 * @author : panBaiKuan
 * @date : 2022/6/212159
 **/
public class FilesUtil {




    /**
     * @param fileUrl url
     * @return void
     * @Description 网络路径下载图片
     * @Author PanBaiKuan
     * @Date 2021/6/21 9:54
     **/
    public static byte[] downFileByUrl(String fileUrl) throws Exception {
        URL url = new URL(fileUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //得到输入流
        InputStream inputStream = conn.getInputStream();
        byte[] bytes = IOUtils.toByteArray(inputStream);
        return bytes;
    }


    /**
     * byte 转file
     */
    public static File byte2File(byte[] buf, File file) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(buf);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }


    /**
     * 获得pdf 每一页的字节数组
     *
     * @param filePath
     * @return List<byte [ ]>
     * @author panBaiKuan
     * @date 2022/7/1 10:40
     */
    public static List<byte[]> getPdfPageBytes(String filePath) throws Exception {
        List<byte[]> arrayList = new ArrayList<>();

        // 根据页码拆分pdf，有多少页就拆成多少张pdf
        File file = new File(filePath);
        PdfReader pdfReader = new PdfReader(new FileInputStream(file));
        int pages = pdfReader.getNumberOfPages();

        for (int i = 1; i <= pages; i++) {
            PdfReader reader = new PdfReader(filePath);
            Document doc = new Document();

            //临时文件
            File tempFile = File.createTempFile(UUID.randomUUID().toString(), ".pdf");
            PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(tempFile));
            doc.open();
            PdfContentByte cb = writer.getDirectContent();
            doc.newPage();
            cb.addTemplate(writer.getImportedPage(reader, i), 0, 0);
            doc.close();
            writer.close();
            reader.close();
            //装成字节数组给前端用
            FileInputStream inputStream = new FileInputStream(tempFile);
            byte[] bytes = IoUtil.readBytes(inputStream);
            arrayList.add(bytes);
            tempFile.delete();
        }
        file.delete();
        return arrayList;
    }



    /**
     * 获得pdf 的页数
     * @author panBaiKuan
     * @date 2022/7/1 17:10
     * @param bytes
     * @return Integer
     */
    public static Integer getPdfPages(byte[] bytes) throws Exception {
        File tempFile = File.createTempFile(UUID.randomUUID().toString(), ".pdf");
        File file = FilesUtil.byte2File(bytes, tempFile);
        // 根据页码拆分pdf，有多少页就拆成多少张pdf
        PdfReader pdfReader = new PdfReader(new FileInputStream(file));
        int pages = pdfReader.getNumberOfPages();
        pdfReader.close();
        file.delete();
        return pages;
    }


    //向文件中写入字符串
    public static void appendWriteFile(File file,String str) throws Exception {
        FileWriter writer = null;
        try {
            writer = new FileWriter(file);
            writer.write(str);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(writer !=null){
                writer.close();
            }
        }
    }



    /**
     * 删除目录（文件夹）以及目录下的文件
     *
     * @param sPath
     *            被删除目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String sPath) {
        // 如果sPath不以文件分隔符结尾，自动添加文件分隔符
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        // 如果dir对应的文件不存在，或者不是一个目录，则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;
        // 删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag){
                    break;
                }
            } // 删除子目录
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag){
                    break;
                }
            }
        }
        if (!flag){
            return false;
        }
        // 删除当前目录
        if (dirFile.delete()) {

            return true;
        } else {
            return false;
        }
    }


    /**
     * 删除单个文件
     *
     * @param sPath
     *            被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

}